package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.swing.text.html.parser.Entity;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Pointcut(value = "execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPonitCut(){}

    @Before("autoFillPonitCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("自动注解启动");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        OperationType operationType = annotation.value();
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        Object entry = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        if (operationType == OperationType.UPDATE) {
            try {
                Method setCreateTime = entry.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                Method setCreateUser = entry.getClass().getDeclaredMethod("setCreateUser", Long.class);
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                entry.getClass().getDeclaredMethod("setUpdateUser",Long.class);
                setCreateTime.invoke(entry,now);
                setCreateUser.invoke(entry,currentId);
                setUpdateTime.invoke(entry,now);
                setUpdateTime.invoke(entry,now);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateTime.invoke(entry,now);
                setUpdateTime.invoke(entry,now);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}

